package com.ruoyi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.JwtHelper;
import com.ruoyi.common.utils.RegexUtils;
import com.ruoyi.common.utils.ThreadLocalUtil;
import com.ruoyi.constants.RedisConstants;
import com.ruoyi.domain.ApUser;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.service.IApUserService;
import com.ruoyi.service.LoginService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IApUserService apUserService;

    @Autowired
    private SysLoginService loginService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public AjaxResult sendCode(String mobile) {
        if (StringUtils.isBlank(mobile)) {
            return AjaxResult.error("手机号不能为空");
        }
        // 1.校验手机号
        boolean invalid = RegexUtils.isPhoneInvalid(mobile);
        // 2.如果不符合，返回错误信息
        if (invalid) {
            return AjaxResult.error("手机号格式错误！");
        }
        String code = RandomStringUtils.randomNumeric(6);
        redisCache.setCacheObject(RedisConstants.LOGIN_CODE_KEY + mobile, code, RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);
        return AjaxResult.success("发送验证码成功", code);
    }

    @Override
    @Transactional
    public AjaxResult login(String mobile, String code) {
        if (StringUtils.isBlank(mobile) || StringUtils.isBlank(code)) {
            return AjaxResult.error("手机号或验证码不能为空");
        }
        String redisMobileCode = redisCache.getCacheObject(RedisConstants.LOGIN_CODE_KEY + mobile);
        if (StringUtils.isBlank(redisMobileCode) || !redisMobileCode.equals(code)) {
            return AjaxResult.error("验证码不正确");
        }

        LambdaQueryWrapper<ApUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApUser::getPhone, mobile);
        ApUser user = apUserService.getOne(queryWrapper);
        if (user == null) {
            user = new ApUser();
            user.setPhone(mobile);
            user.setName("Blog" + code);
            user.setImage("https://img.51miz.com/Element/00/26/90/33/0478fd1b_E269033_a8fb6a07.png");
            user.setCreatedTime(LocalDateTime.now());
            // 未锁定 正常
            user.setStatus(false);
            apUserService.save(user);
        } else if (user.getStatus()) {
            return AjaxResult.error("您的账号已被锁定，请联系管理员");
        }

        String token = JwtHelper.createToken(user.getId(), user.getPhone());
        Map<String, Object> data = new HashMap<>();
        data.put("userInfo", user);
        data.put("token", token);
        return AjaxResult.success("登录成功", data);
    }
}
